import paramiko
import re


def get_ssh_connection(ip, username, password):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ip, username=username, password=password)
    return ssh


def execute_command(ssh, command):
    stdin, stdout, stderr = ssh.exec_command(command)
    return stdout.read().decode()


def get_device_info(ssh):
    """获取设备基础信息"""
    output = execute_command(ssh, 'show version')

    # 设备型号
    model = re.search(r'System description\s+:\s+([^\s]+(?: [^\s]+)*)', output)
    print(f"[XJ]系统信息-设备型号#{model.group(1) if model else '未知'}#正常#获取设备信息#无")

    # 系统版本
    version = re.search(r'System software version\s*:\s*(\S+)', output)
    print(f"[XJ]系统信息-软件版本#{version.group(1).strip() if version else '未知'}#正常#获取系统版本#无")

    # 运行时间
    uptime = re.search(r'System uptime\s*:\s*(\d+:\d+:\d+:\d+)', output)
    print(f"[XJ]系统信息-运行时长#{uptime.group(1).strip() if uptime else '未知'}#正常#获取运行时间#无")


def get_status_info(ssh, ip, username, password):
    """获取设备状态信息"""
    # 电源状态
    ssh = get_ssh_connection(ip, username, password)
    power_status = execute_command(ssh, 'show power')
    for line in power_status.splitlines():
        if re.search(r'RG-', line) and ("ok" in line or "fault" in line):
            columns = line.split()
            print(f"[XJ]状态指标-电源{columns[0]}状态#{columns[2]}#正常#电源状态检测#无")

    ssh.close()

    # 风扇状态
    ssh = get_ssh_connection(ip, username, password)
    fan_status = execute_command(ssh, 'show fan')
    for line in fan_status.splitlines():
        if re.match(r'^\d+', line):
            fan_id = line.split()[0]
            status = line[24:34].strip()
            if status == "ok":
                print(f"[XJ]状态指标-风扇{fan_id}状态#{status}#正常#风扇正常#无")
            else:
                print(f"[XJ]状态指标-风扇{fan_id}状态#{status}#异常#风扇不正常#无")
    ssh.close()

    # 接口状态
    ssh = get_ssh_connection(ip, username, password)
    interface_status = execute_command(ssh, 'show interface status')
    for line in interface_status.splitlines():
        if re.match(r'^(TenGigabitEthernet|HundredGigabitEthernet|AggregatePort)', line):
            interface = line[:40].strip()
            status = line[40:49].strip()
            print(f"[XJ]接口-{interface}#{status}#正常#接口状态up#无")
    ssh.close()


def get_performance_info(ssh, ip, username, password):
    """获取性能指标"""
    # CPU信息
    ssh = get_ssh_connection(ip, username, password)
    cpu_info = execute_command(ssh, 'show cpu')
    match = re.search(r'CPU utilization in five minutes:\s*([\d.]+)%', cpu_info)
    if match:
        cpu_usage = match.group(1)
        if cpu_usage < '50':
            print(
                f"[XJ]性能指标-5分钟平均使用率#{cpu_usage}%#正常#CPU使用率小于50%#无")
        else:
            print(
                f"[XJ]性能指标-5分钟平均使用率#{cpu_usage}%#异常#CPU使用率大于等于50%#无")
    else:
        print("未能获取 CPU 5分钟平均使用率")
    ssh.close()

    # 内存使用率
    ssh = get_ssh_connection(ip, username, password)
    memory_info = execute_command(ssh, 'show memory')
    match = re.search(r'(\d+\.\d+)% used rate', memory_info)
    if match:
        memory_usage = match.group(1)
        if memory_usage < '50':
            print(f"[XJ]性能指标-内存使用率#{memory_usage}#正常#内存使用率小于50%#无")
        else:
            print(f"[XJ]性能指标-内存使用率#{memory_usage}#异常#内存使用率大于等于50%#请检查")
    ssh.close()

    # 温度信息
    ssh = get_ssh_connection(ip, username, password)
    temperature_info = execute_command(ssh, 'show temperature')
    #print(temperature_info)
    print("温度传感器状态 (Temperature Name - Current °C):")
    lines = temperature_info.splitlines()
    for line in lines:
        if len(line) >= 68:  # 确保行长度足够
            #print(line)
            if any([
                "Temperature" in line,
                re.search(r'-{4,}', line[41:65])
            ]):
                continue
            temp_name = line[41:65].strip()  # 42-65字符位置
            current_temp = line[66:68].strip()  # 67-68字符位置
            if current_temp < '60':
                print(f"[XJ]状态指标-{temp_name}温度#{current_temp}°C#正常#温度小于60#无")
            else:
                print(f"[XJ]状态指标-{temp_name}温度#{current_temp}°C#异常#温度大于等于50#请检查")
    ssh.close()


def main():
    ip = "10.2.245.146"
    username = "yunwei-admin"
    password = "Sinotruk@2516"

    try:
        ssh = get_ssh_connection(ip, username, password)
        get_device_info(ssh)
        get_status_info(ssh, ip, username, password)
        get_performance_info(ssh, ip, username, password)
    except Exception as e:
        print(f"[XJ]系统信息-连接状态#已连接#正常#SSH连接#无")


if __name__ == "__main__":
    main()